package scheduler

import (
	"context"
	"log"
	"time"

	"github.com/ammyhaber/seckill/service/inventory/service"
)

// InventoryScheduler 库存相关定时任务调度器
type InventoryScheduler struct {
	inventoryLockService *service.InventoryLockService
	stopChan             chan struct{}
	isRunning            bool
}

// NewInventoryScheduler 创建库存定时任务调度器
func NewInventoryScheduler(inventoryLockService *service.InventoryLockService) *InventoryScheduler {
	return &InventoryScheduler{
		inventoryLockService: inventoryLockService,
		stopChan:             make(chan struct{}),
	}
}

// Start 启动定时任务
func (s *InventoryScheduler) Start() {
	if s.isRunning {
		return
	}
	s.isRunning = true

	// 启动处理超时库存锁定记录的定时任务
	go s.scheduleProcessExpiredLocks()

	log.Println("库存定时任务调度器已启动")
}

// Stop 停止定时任务
func (s *InventoryScheduler) Stop() {
	if !s.isRunning {
		return
	}

	close(s.stopChan)
	s.isRunning = false
	log.Println("库存定时任务调度器已停止")
}

// scheduleProcessExpiredLocks 定时处理超时的库存锁定记录
func (s *InventoryScheduler) scheduleProcessExpiredLocks() {
	// 设置定时器，每3分钟执行一次
	ticker := time.NewTicker(3 * time.Minute)
	defer ticker.Stop()

	// 启动后立即执行一次
	s.processExpiredLocks()

	for {
		select {
		case <-ticker.C:
			s.processExpiredLocks()
		case <-s.stopChan:
			return
		}
	}
}

// processExpiredLocks 处理超时的库存锁定记录
func (s *InventoryScheduler) processExpiredLocks() {
	ctx := context.Background()

	// 设置超时时间为30分钟
	expireDuration := 30 * time.Minute

	log.Println("开始处理超时的库存锁定记录")
	if err := s.inventoryLockService.ProcessExpiredLocks(ctx, expireDuration); err != nil {
		log.Printf("处理超时库存锁定记录失败: %v\n", err)
	} else {
		log.Println("处理超时库存锁定记录完成")
	}
}
